Python 3.6 for beginners
__TOC__ I strongly recommend installing Anaconda (Python distribution). It comes with numpy and scipy preinstalled. Anaconda also comes with Spyder which makes it much easier to find and correct errors. Comments # comments follow a pound sign Help Variables : Back to top Dictionaries Ordered lists Back to top Input and output print(name, "is", age, "years old") # default separater is a single space. default end is new line print("this is printed on a new line") print("But we can change the def", "ault separator and default end", sep="", end="") print("This is not printed on a new line") print("a\tbx\tc\n12345678901234567890") # \t is tab and \n is new line. your_input = input("please enter your input: ") john is 36 years old this is printed on a new line But we can change the default separator and default endThis is not printed on a new line a bx c 12345678901234567890 please enter your input: Back to top Loops : for num in range(1000, 2000, 100): # prints 1000 to 1900 in steps of 100 ::print (num) num = 0 while num < 100000000: # Thats 100,000,000. It runs in about 10 seconds ::num = num + 1 Back to top Conditional statements : young = age < 10 old = age > 65 middle_age = (45 < age < 65) if young: # dont forget the colon at the end ::print (name, "is young") elif old: ::print (name, "is old") elif middle_age: ::print (name, "is middle age") else: ::print (name, "is neither young nor old nor middle age") Back to top Functions : def convert_to_celcius(fahrenheit): ::"""Converts fahrenheit to celcius""" # documentation that is printed out when we use help("convert_to_celcius") ::return (fahrenheit-32)*5/9 print (convert_to_celcius(212)) Back to top Importing modules There is nothing fancy about a module. Its just a program containing program definitions. The program is executed when it is imported unless it was previously imported. You can easily create your own modules. After importing a module you can use help("module name") to get info. ::Template:Help("time") ::Template:Help("math") dir(module_name) # returns a list of all the functions in the module. Easier to read if converted to an array. import time time.sleep(15) # delay for 15 seconds import math x = math.sqrt(9) # x = sqrt(9) wont work. You must use math.sqrt import math as mt x = mt.sqrt(9) from math import sqrt x = sqrt(9) # no need for math.sqrt since sqrt has been imported into the current namespace Back to top Classes Tutorial Calling methods is very similar to calling functions in a module. Instead of module.function(arguments) you use class.method(arguments). str.capitalize("string") # returns the string with first letter capitalized In a perfect world modules and classes would be the same thing because every module would correspond to exactly one class of object. But we dont live in that world. type(any_object) # returns the class of the object When we call a method, the object itself is passed as the first parameter (called "self"). class Person: :def __init__(self, name, birthday): ::self.name = name ::self.birthday = birthday :def age(self): ::today = datetime.date.today() ::age = today.year - self.birthdate.year ::return age person1 = Person("Bill", datetime.date(1981, 12, 27) ) Back to top Text files with open("TextFile.txt", "r") as file: ::contents = file.read() with open("TextFile.txt", "r") as file: ::List_of_lines = file.readlines() with open("TextFile.txt", "w") as output_file: ::output_file.write(contents) Back to top Database Creating: import sqlite3 con = sqlite3.connect('test.db') cur = con.cursor() cur.execute('CREATE TABLE test(name TEXT, age INTEGER)') cur.execute('INSERT INTO test VALUES("John", 33)') cur.execute('INSERT INTO test VALUES("Alice", 21)') x=18 cur.execute('INSERT INTO test VALUES(?, ?)', x) con.commit() # changes are not committed until this command cur.execute('SELECT * FROM test WHERE age > 5 ORDER BY name') whole_table = cur.fetchall() print (whole_table) con.close() Updating" import sqlite3 con = sqlite3.connect('test.db') cur = con.cursor() cur.execute('DELETE FROM test WHERE name = "John"') cur.execute('UPDATE test SET age = 99 WHERE name = "Alice"') # if there is more than one Mary then they both get updated cur.execute('SELECT * FROM test WHERE age > 5 ORDER BY name') whole_table = cur.fetchall() print (whole_table) con.close() Back to top Pandas Tutorial and Cheatsheet pandas = panels of data (multi-dimensional data) A pandas dataframe (spreadsheet) is normally created from a list or a list of lists. We could create a dataframe from an array but then all the data would have to be of the same type. Back to top Internet The following code prints each line of the webpage minus most of the html markup. tag = False quote = False import urllib.request with urllib.request.urlopen("https://en.wikipedia.org/wiki/Hiroshi_Sakagami") as webpage: ::for line in webpage: :::out = "" :::line = line.strip() :::line = line.decode('utf-8') :::if line "": ::::print (line) :::elif line0:7 "": ::::line = "" :::else: ::::for c in line: :::::if c '<' and not quote: ::::::tag = True :::::elif c '>' and not quote: ::::::tag = False :::::elif (c '"' or c "'") and tag: ::::::quote = not quote :::::elif not tag: ::::::out = out + c ::::if out != "": :::::print(out) x=input("press enter when done") Back to top Numpy Arrays numpy arrays are fast because they work with continuous blocks of memeory. import numpy as np x = np.array([1,2,3,4,5,6]) print (x) [2 3 5 6] Math operations + and * operate elementwise and create a new matrix. To modify an existing array use += and *= For matrix multiplication use @ Back to top Scipy tutorial To import two subpackages you would use: from scipy import subpackage1, subpackage2 import scipy as sp from scipy import constants print (constants.physical_constantsparticle mass") # produces the following tuple: (6.64465723e-27, 'kg', 8.2e-35) Back to top Sympy Galgebra tutorial Back to top Matplotlib Tutorial The Matplotlib API Bizarrely, in matplotlib.pyplot states are preserved across function calls. See also: subplots Back to top Jupyter Tutorial Back to top External links * https://snakify.org/en/ (for teachers) * https://www.packtpub.com/tech/Python Copyright